"use strict";
const { app, BrowserWindow, ipcMain, screen, Tray, Menu, dialog, shell, Notification, globalShortcut } = require("electron");
const path = require("path");
const { exec } = require("child_process");
const screenshotHandler = require("../src/utils/screenshot");
const DialogManager = require("../src/utils/dialogManager");
process.env["ELECTRON_DISABLE_SECURITY_WARNINGS"] = process.env.NODE_ENV === "production" ? "false" : "true";
let win;
let isMinimized = false;
let originalBounds;
let appTray = null;
const createWindow = () => {
  const isDev = !!process.env.VITE_DEV_SERVER_URL;
  win = new BrowserWindow({
    width: 800,
    height: 600,
    frame: false,
    //顶部菜单显隐 必须关闭才有透明效果
    transparent: true,
    backgroundColor: "rgba(0, 0, 0, 0.45)",
    movable: true,
    resizable: true,
    icon: path.join(__dirname, "../public/logo.ico"),
    webPreferences: {
      webSecurity: process.env.NODE_ENV === "production",
      // 允许跨协议请求
      allowRunningInsecureContent: isDev,
      // 允许混合内容
      nodeIntegration: true,
      // 集成node api
      contextIsolation: true,
      // 启用上下文隔离（安全！）
      webviewTag: true,
      preload: path.join(__dirname, "preload.js")
    }
  });
  if (isDev) {
    win.loadURL(process.env.VITE_DEV_SERVER_URL);
    win.webContents.openDevTools();
  } else {
    win.loadFile(path.join(__dirname, "../dist/index.html"));
  }
  setupTray();
};
const setupTray = () => {
  const trayMenuTemplate = [
    {
      label: "打开应用",
      click: function() {
        win.show();
      }
    },
    {
      label: "应用设置",
      click: function() {
      }
    },
    {
      label: "退出应用",
      click: function() {
        app.quit();
      }
    }
  ];
  let iconPath = path.join(__dirname, "../public/logo.ico");
  appTray = appTray || new Tray(iconPath);
  const contextMenu = Menu.buildFromTemplate(trayMenuTemplate);
  appTray.setContextMenu(contextMenu);
  appTray.setToolTip("管小花");
  const handleTrayClick = () => {
    win.setAlwaysOnTop(true, "floating");
    win.show();
    const blurHandler = () => {
      win.setAlwaysOnTop(false);
      win.off("blur", blurHandler);
    };
    win.off("blur", blurHandler);
    win.on("blur", blurHandler);
  };
  appTray.removeAllListeners("click");
  appTray.on("click", handleTrayClick);
};
let floatWindow = null;
const createFloatWindow = () => {
  floatWindow = new BrowserWindow({
    frame: false,
    transparent: true,
    backgroundColor: "rgba(0, 0, 0, 0.45)",
    resizable: false,
    movable: true,
    alwaysOnTop: true,
    webPreferences: {
      webSecurity: process.env.NODE_ENV === "production",
      // 允许跨协议请求
      nodeIntegration: true,
      // 集成node api
      contextIsolation: true,
      // 启用上下文隔离（安全！）必须，不然通信preload无效
      webviewTag: true,
      preload: path.join(__dirname, "preload.js")
    }
  });
  if (process.env.VITE_DEV_SERVER_URL) {
    floatWindow.loadURL(process.env.VITE_DEV_SERVER_URL + "#/float");
    floatWindow.webContents.openDevTools();
  } else {
    floatWindow.loadFile(path.join(__dirname, "../dist/index.html"), { hash: "#/float" });
  }
  floatWindow.webContents.on("ipc-message", (_, message) => {
    if (message === "drag-start") {
      const [x, y] = floatWindow.getPosition();
    }
  });
  floatWindow.on("closed", () => floatWindow = null);
};
app.whenReady().then(() => {
  createWindow();
  app.on("activate", () => {
    if (BrowserWindow.getAllWindows().length === 0) createWindow();
  });
});
app.on("window-all-closed", () => {
  if (process.platform !== "darwin") app.quit();
});
app.on("ready", () => {
  let ret = globalShortcut.register("ctrl + q", () => {
    console.log("ctrl + q is pressed");
  });
  if (!ret) {
    console.log("register globalShortcut failed");
    return false;
  }
});
app.on("will-quit", () => {
  globalShortcut.unregister("ctrl + q");
  globalShortcut.unregisterAll();
});
ipcMain.on("showError", (event, data) => {
  DialogManager.showErrorDialog(data.title, data.content);
});
ipcMain.on("openFile", (event, data) => {
  console.log(data);
  DialogManager.openFileDialog(data).then((res) => {
    console.log(res);
  });
});
ipcMain.on("saveFile", (event, data) => {
  DialogManager.showSaveDialog(data).then((res) => {
    console.log(res);
  });
});
ipcMain.on("showMessage", (event, data) => {
  DialogManager.showMessage(data).then((res) => {
    console.log(res);
  });
});
ipcMain.on("test", (event, data) => {
  const NOTIFICATION_TITLE = "Basic Notification";
  const NOTIFICATION_BODY = "Notification from the Main process";
  console.log(11111);
  new Notification({
    title: NOTIFICATION_TITLE,
    body: NOTIFICATION_BODY
  }).show();
});
ipcMain.on("quit", () => {
  DialogManager.showMessage({
    type: "info",
    title: "确认",
    message: "确定要退出应用程序吗？",
    buttons: ["取消", "确定"]
  }).then((res) => {
    if (res.response === 1) {
      app.quit();
    }
  });
});
ipcMain.on("notOpen", () => {
  DialogManager.showMessage({
    message: "该功能暂未开放，敬请期待！"
  }).then((res) => {
  });
});
ipcMain.on("toggleWindow", () => {
  const { width, height } = screen.getPrimaryDisplay().workAreaSize;
  console.log(isMinimized, win.getBounds());
  if (!isMinimized) {
    originalBounds = win.getBounds();
    const newWidth = 410;
    const newHeight = 500;
    win.setBounds({
      x: width - newWidth - 50,
      y: 100,
      width: newWidth,
      height: newHeight
    });
  } else {
    win.setBounds(originalBounds);
    win.center();
  }
  isMinimized = !isMinimized;
});
ipcMain.on("adjust-height", (event, height) => {
  const [currentWidth] = win.getSize();
  win.setSize(currentWidth, Math.floor(height), true);
});
ipcMain.on("goTray", (event, data) => {
  win.hide();
});
ipcMain.on("screenShots", () => {
  if (process.platform === "darwin") {
    screenshotHandler.handleScreenShots(win);
  } else {
    screenshotHandler.screenWindow(win);
  }
});
ipcMain.handle("chooseFile", () => {
  const { canceled, filePaths } = dialog.showOpenDialog(
    {
      title: "选择文件",
      properties: ["openFile", "multiSelections"]
    }
  );
  if (!canceled) {
    return filePaths[0];
  }
});
ipcMain.on("goLink", (event, data) => {
  shell.openExternal(data).then((res) => {
  });
});
ipcMain.on("calculator", () => {
  let command;
  switch (process.platform) {
    case "win32":
      command = "calc.exe";
      break;
    case "darwin":
      command = "open /System/Applications/Calculator.app";
      break;
    case "linux":
      command = "gnome-calculator || kde-calculator || xdg-open calculator:";
      break;
    default:
      console.error("Unsupported platform");
      return;
  }
  exec(command, (error) => {
    if (error) {
      DialogManager.showErrorDialog("提示", "无法打开计算器");
    }
  });
});
ipcMain.on("changeBgColor", (event, data) => {
  console.log(data);
  win.setBackgroundColor(data);
  console.log(win.getBackgroundColor());
});
ipcMain.on("showFloatBall", (event, bounds) => {
  const { workAreaSize } = screen.getPrimaryDisplay();
  if (bounds.turnIntoABall) {
    win.hide();
    if (!floatWindow || floatWindow.isDestroyed()) {
      createFloatWindow();
    } else {
      floatWindow.show();
    }
    floatWindow.setBounds({
      x: workAreaSize.width - 300,
      y: workAreaSize.height - 300,
      width: 200,
      height: 200
    });
  } else {
    win.show();
    if (floatWindow) floatWindow.hide();
  }
});
ipcMain.handle("getScreenInfo", () => {
  const { workAreaSize, size } = screen.getPrimaryDisplay();
  return {
    workAreaSize,
    size
  };
});
ipcMain.handle("getPosition", (event, data) => {
  if (floatWindow && !floatWindow.isDestroyed()) {
    const [x, y] = floatWindow.getPosition();
    console.log(x, y);
    return { x, y };
  }
  return { x: 0, y: 0 };
});
ipcMain.on("setPosition", (event, { x, y }) => {
  if (floatWindow && !floatWindow.isDestroyed()) {
    const { workAreaSize } = screen.getPrimaryDisplay();
    const maxX = workAreaSize.width - 50;
    const maxY = workAreaSize.height - 50;
    const clampedX = Math.max(0, Math.min(x, maxX));
    const clampedY = Math.max(0, Math.min(y, maxY));
    floatWindow.setPosition(clampedX, clampedY);
  }
});
ipcMain.handle("get-window-size", () => {
  if (floatWindow && !floatWindow.isDestroyed()) {
    const size = floatWindow.getSize();
    return size;
  }
  return [200, 200];
});
